package com.chookss.home.document;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.tools.MyToast;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lvgroup.hospital.base.BaseAct;
import com.tencent.tbs.reader.ITbsReader;
import com.tencent.tbs.reader.ITbsReaderCallback;
import com.tencent.tbs.reader.TbsFileInterfaceImpl;

import org.jetbrains.annotations.Nullable;

//打开本地文件，不做其他操作
public class DocumentLocalPreviewActivity extends BaseAct {
    private FrameLayout pdf_rl;
    private TextView tvTiltle;
    private RelativeLayout title;
    private ImageView iv_DataBaseBack;
    private LinearLayout common_right_iv_ll;
    private LinearLayout common_collect_ll;
    private String fileName, fileUrl;
    private boolean isDestroyed = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_document_preview);
    }

    @Override
    public void initData() {
        initState();
        MyApp.docunmentOpen = true;
        iv_DataBaseBack = findViewById(R.id.iv_DataBaseBack);
        title = findViewById(R.id.title);
        tvTiltle = findViewById(R.id.tvTiltle);
        pdf_rl = findViewById(R.id.pdf_rl);
        common_right_iv_ll = findViewById(R.id.common_right_iv_ll);
        common_collect_ll = findViewById(R.id.common_collect_ll);
        common_right_iv_ll.setVisibility(View.GONE);
        common_collect_ll.setVisibility(View.GONE);
        iv_DataBaseBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        fileUrl = getIntent().getStringExtra("fileUrl");
        fileName = getIntent().getStringExtra("fileName");
        tvTiltle.setText(getIntent().getStringExtra("fileName"));
        KLog.i(fileUrl);
        openFile(fileUrl, parseFormat(fileUrl));
    }

    private void openFile(String filePath, String fileExt) {
        //设置回调
        ITbsReaderCallback callback = new ITbsReaderCallback() {
            @Override
            public void onCallBackAction(Integer actionType, Object args, Object result) {
                if (args instanceof Bundle) {
                    int id = ((Bundle) args).getInt("typeId");
                    if (ITbsReader.TBS_READER_TYPE_STATUS_UI_SHUTDOWN == id) {
                        finish();       // 加密文档弹框取消需关闭activity
                    }
                }
            }
        };
        Bundle param = new Bundle();
        param.putString("filePath", filePath);
        param.putString("fileExt", fileExt); // 文件后缀名，如文件名为test.pdf，则只需要传入"pdf"
        param.putString("tempPath", getExternalFilesDir("temp").getAbsolutePath());
        //调用openFileReader打开文件
        pdf_rl.post(new Runnable() {
            @Override
            public void run() {
                int height = pdf_rl.getHeight();
                param.putInt("set_content_view_height", height); // 文档内容的显示区域高度，自定义layout模式必须传入这个值
                try {
                    int ret = TbsFileInterfaceImpl.getInstance().openFileReader(
                            DocumentLocalPreviewActivity.this, param, callback, pdf_rl);
                } catch (Exception e) {
                    e.printStackTrace();
                    MyToast.show("打开异常，请检查文件后重试");
                    finish();
                }
            }
        });
    }


    private String parseFormat(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    // 销毁资源使用onpause + ondestroy的方式。避免onDestroy延迟回调
    private void destroy() {
        if (isDestroyed) {
            return;
        }
        // 回收资源
        pdf_rl.removeAllViews(); //移除内容显示区域layout
        try {
            TbsFileInterfaceImpl.getInstance().closeFileReader(); //关闭fileReader
        } catch (Exception e) {
            e.printStackTrace();
        }
        isDestroyed = true;
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) {
            destroy();
        }
    }

    //横屏切换
    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) this).getWindowManager().getDefaultDisplay().getMetrics(dm);
        int w = dm.widthPixels;
        int h = dm.heightPixels - title.getHeight();
        TbsFileInterfaceImpl.getInstance().onSizeChanged(w, h);
    }

    @Override
    protected void onDestroy() {
        MyApp.docunmentOpen = false;
        destroy();
        super.onDestroy();
    }

}
